<?php

namespace App\Admin\Controllers;

use App\Models\Student;
use App\Models\Grade;
use App\Models\Major;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class StudentManagementController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('学生管理')
            ->description('学生信息')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('学生管理')
            ->description('学生详细信息')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('学生管理')
            ->description('编辑学生信息')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('学生管理')
            ->description('新建学生信息')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Student);

        $grid->model()->where('id', '>', 0);
        $grid->id('Id')->sortable();
        $grid->student_id('学号');
        $grid->name('姓名');
        $grid->sex('性别')->display(function ($sex) {
            $sexStr = '';
            $color = '#D4D8DB';
            switch ($sex) {
                case '0':
                    $color = '#587EB7';
                    $sexStr = '男';
                    break;
                case '1':
                    $color = '#CE4C92';
                    $sexStr = '女';
                    break;
                case '2':
                    $sexStr = '其他';
                    break;
            }
            return "<span style='color: $color'>$sexStr</span>";
        });
        $grid->birthday('生日');
        $grid->nation('民族');
        $grid->id_card('身份证');
        $grid->mobile('手机');
        $grid->enrollment_date('入学日期');
        $grid->boarder('是否住宿')->display(function ($boarder) {
            $boarder ? $boarderStr = '住宿生': $boarderStr = '走读生';
            return $boarderStr;
        });
        $grid->school_tag('毕业学校');
        $grid->native_place('籍贯');
        $grid->graduation('是否毕业')->display(function ($graduation) {
            $graduation ? $graduationStr = '已毕业': $graduationStr = '未毕业';
            $graduation ? $color = '#FF4500': $color = '#32CD32';
            return "<span style='color: $color'>$graduationStr</span>";
        });
        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 在这里添加字段过滤器
            $filter->column(1/2, function ($filter) {
                $filter->like('student_id', '学号');
                $filter->like('name', '姓名');
                $filter->like('id_card', '身份证');
            });

            $filter->column(1/2, function ($filter) {
                $filter->equal('sex','性别')->select([0  =>  '男', 1 => '女', 2 => '其他']);
                $filter->equal('boarder', '是否住宿')->radio([
                    1 => ' 住宿生',
                    0 => ' 走读生',
                ]);
                $filter->equal('graduation', '是否毕业')->radio([
                    1 => ' 已毕业',
                    0 => ' 未毕业',
                ]);
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Student::findOrFail($id));

        $show->picture('照片')->image('','150','150');
        $show->student_id('学号');
        $show->name('姓名');
        $show->birthday('出生日期');
        $show->sex('性别')->as(function ($sex) {
            $sexStr = '';
            switch ($sex) {
                case '0':
                    $sexStr = '男';
                    break;
                case '1':
                    $sexStr = '女';
                    break;
                case '2':
                    $sexStr = '其他';
                    break;
            }
            return $sexStr;
        });
        $show->id_card('身份证');
        $show->nation('民族');
        $show->health('健康状态');
        $show->enrollment_date('入学日期');
        $show->politics_status('政治面貌')->as(function ($politicsStatus) {
            $maritalStatusArr = [
                '01' => '中共党员',
                '02' => '中共预备党员',
                '03' => '共青团员',
                '04' => '群众'
            ];
            $politicsStatus = $maritalStatusArr[$politicsStatus];

            return $politicsStatus;
        });
        $show->boarder('是否住宿')->as(function ($boarder) {
            return $boarder ? $boarder = '住宿生': $boarder = '走读生';
        });
        $show->major_id('专业')->as(function ($major_id) {
            $major = Major::where('id', $major_id)->first();
            return $major->title;
        });
        $show->class_id('班级')->as(function ($class_id) {
            $class = Grade::where('id', $class_id)->first();
            return $class->class_name;
        });
        $show->seat('座位号');
        $show->mobile('手机号');
        $show->qq('QQ');
        $show->email('邮箱');
        $show->school_tag('毕业学校');
        $show->native_place('籍贯');
        $show->cm('户籍所在地');
        $show->home_address('家庭住址');
        $show->home_zip_code('家庭邮编');
        $show->home_phone('家庭电话');
        $show->home_phone('父亲姓名');
        $show->father_phone('父亲电话');
        $show->mother_name('母亲姓名');
        $show->mother_phone('母亲电话');
        $show->graduation('是否毕业')->as(function ($graduation) {
            return $graduation ? $graduation = '已毕业': $graduation = '未毕业';
        });

        $show->created_at('创建日期');
        $show->updated_at('修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Student);

        $form->hidden('user_id');
        $form->text('student_id', '学号')->setWidth(2, 2)->rules('required', [
            'required' => '学号必填'
        ]);
        $form->text('name', '姓名')->setWidth(2, 2)->rules('required', [
            'required' => '学生姓名必填'
        ]);
        $form->date('birthday', '出生日期')->default(date('Y-m-d'));
        $form->radio('sex','性别')->options(['0' => ' 男', '1' => ' 女', '2' => ' 其他']);
        $form->text('id_card', '身份证')->setWidth(2, 2)->rules('required', [
            'required' => '学生身份证必填'
        ]);
        $form->image('picture', '照片')->uniqueName()->setWidth(3, 2);
        $form->select('nation','民族')->options(['汉族' => '汉族', '壮族' => '壮族', '回族' => '回族', '满族' => '满族', '维吾尔族' => '维吾尔族', '苗族' => '苗族', '彝族' => '彝族', '土家族' => '土家族', '藏族' => '藏族', '蒙古族' => '蒙古族', '侗族' => '侗族', '布依族' => '布依族', '瑶族' => '瑶族', '白族' => '白族', '朝鲜族' => '朝鲜族', '哈尼族' => '哈尼族', '黎族' => '黎族', '哈萨克族' => '哈萨克族', '傣族' => '傣族', '畲族' => '畲族', '傈僳族' => '傈僳族', '东乡族' => '东乡族', '仡佬族' => '仡佬族', '拉祜族' => '拉祜族', '佤族' => '佤族', '水族' => '水族', '纳西族' => '纳西族', '羌族' => '羌族', '土族' => '土族', '仫佬族' => '仫佬族', '锡伯族' => '锡伯族', '柯尔克孜族' => '柯尔克孜族', '景颇族' => '景颇族', '达斡尔族' => '达斡尔族', '撒拉族' => '撒拉族', '布朗族' => '布朗族', '毛南族' => '毛南族', '塔吉克族' => '塔吉克族', '普米族' => '普米族', '阿昌族' => '阿昌族', '怒族' => '怒族', '鄂温克族' => '鄂温克族', '京族' => '京族', '基诺族' => '基诺族', '德昂族' => '德昂族', '保安族' => '保安族', '俄罗斯族' => '俄罗斯族', '裕固族' => '裕固族', '乌孜别克族' => '乌孜别克族', '门巴族' => '门巴族', '鄂伦春族' => '鄂伦春族', '独龙族' => '独龙族', '赫哲族' => '赫哲族', '高山族' => '高山族', '珞巴族' => '珞巴族', '塔塔尔族' => '塔塔尔族'])->setWidth(2, 2);
        $form->select('health', '健康状态')->options(['健康' => '健康', '亚健康' => '亚健康', '疾病' => '疾病'])->setWidth(2, 2);
        $form->select('politics_status', '政治面貌')->options(['01' => '中共党员', '02' => '中共预备党员', '03' => '共青团员', '04' => '群众'])->setWidth(2, 2);

        $form->date('enrollment_date', '入学日期')->default(date('Y-m-d'));
        $form->radio('boarder', '是否住宿')->options([0 => '走读生' , 1 => '住宿生']);

        $majors = Major::where('parent_id','<>', '0')->get();
        $major_arr = [];
        foreach ($majors as $major) {
            $major_arr[$major->id] = $major->title;
        }

        $form->select('major_id', '专业')->options($major_arr)->load('class_id', 'api/class')->setWidth(2, 2);
        $form->select('class_id', '班级')->options(function ($id){
            return Grade::where('id', $id)->pluck('class_name' , 'id');
        })->setWidth(2, 2);

        $form->text('seat', '座位号')->setWidth(2, 2);
        $form->mobile('mobile', '手机号');
        $form->text('qq', 'QQ')->setWidth(2, 2);
        $form->email('email', '邮箱')->setWidth(2, 2);
        $form->text('school_tag', '毕业学校')->setWidth(2, 2);
        $form->text('native_place', '籍贯')->setWidth(2, 2);
        $form->text('cm', '户籍所在地')->setWidth(4, 2);
        $form->text('father_name', '父亲姓名')->setWidth(2, 2);
        $form->mobile('father_phone', '父亲电话')->setWidth(2, 2);
        $form->text('mother_name', '母亲姓名')->setWidth(2, 2);
        $form->mobile('mother_phone', '母亲电话')->setWidth(2, 2);
        $form->text('home_zip_code', '家庭邮编')->setWidth(2, 2);
        $form->text('home_phone', '家庭电话')->setWidth(2, 2);
        $form->text('home_address', '家庭住址')->setWidth(4, 2);
        $form->switch('graduation', '是否毕业')->states([ 'on'  => ['value' => 1, 'text' => '是'], 'off' => ['value' => 0, 'text' => '否'],]);
        $form->footer(function ($footer) {
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
        });

        $form->saving(function ($model) {

            $id = $model->model()->id;

            //判断是否有id
            if(!$id){
                $request = request()->all();
                $studentId = $request['student_id'];
                $cardId = $request['id_card'];
                $studentResult = Student::where('student_id', $studentId)->first();
                $cardResult = Student::where('id_card', $cardId)->first();
                if(!empty($studentResult) or !empty($cardResult)){
                    $title = '提示';
                    $message = '学号或身份证号已存在';
                }

                $classId = $request['class_id'];
                $seat = $request['seat'];
                $seatResult = Student::where('class_id', $classId)->where('seat', $seat)->first();

                if(!empty($seatResult)) {
                    $title = '提示';
                    $message = '座号已存在';
                }

                if(!empty($title)){
                    $error = new MessageBag([
                        'title'   => $title,
                        'message' => $message,
                    ]);
                    return back()->with(compact('error'))->withInput();
                }
            }

            $username = $model->student_id;
            $name = $model->name;
            $user_id = $model->user_id;
            $admin_user = DB::table('admin_users')->where('id', $user_id)->first();
            $datetime = date('Y-m-d H:i:s');
            if(!empty($admin_user)) {
                DB::table('admin_users')->where('id', $user_id)->update([
                    'username' => "$username"
                    ,'name' => "$name"
                    ,'updated_at' => "$datetime"
                ]);
            }else {
                $password = bcrypt('123456');
                $userId = DB::table('admin_users')->insertGetId([
                    'username' => "$username"
                    ,'password' => "$password"
                    ,'name' => "$name"
                    ,'created_at' => "$datetime"
                    ,'updated_at' => "$datetime"
                ]);
                DB::table('admin_role_users')->insert([
                    'role_id' => 3
                    ,'user_id' => $userId
                ]);
                $model->user_id = $userId;
            }
        });
        return $form;
    }

}
